/**
 *  Copyright (C) 2013  Piotr Szczepa�ski
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package edu.pw.elka.gtsna.arnetminer;

import java.util.LinkedHashMap;


import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.pw.elka.gtsna.graph_creator.GraphCommunityStructureReader;

/**
 * @author Piotr Lech Szczepa�ski
 * @author P.Szczepanski@ii.pw.edu.pl 
 *
 */
public class ArnetMinerV14PartitionReader extends GraphCommunityStructureReader{
	
	protected Map<String, Integer> partitions = new LinkedHashMap<String, Integer>();
	protected int partitionsNumber = 0;
	
	public ArnetMinerV14PartitionReader(String fileName) {
		super(fileName);
		readLine(); 		
		
		while (hasNext() && !isLineVenue()){
			readLine(); 		
		}	
	}

	
	private boolean isLineIndex() {
		return (newLine.length() >= 6 && newLine.substring(0, 6).equals("#index"));
	}
	
	private boolean isLineVenue() {
		return (newLine.length() >= 2 && newLine.substring(0, 2).equals("#c"));
	}
	
	private String extractVenue(String line){
		String regex = "\\s\\d\\dth\\s";

		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(line);
		StringBuffer sb = new StringBuffer();

		while (m.find()) {
		    m.appendReplacement(sb, " ");
		}

		m.appendTail(sb);

		return sb.toString().substring(2);
	}

	@Override
	public List<Integer> next() {

		String venue = "";
		
		List<Integer> nodePartition = new LinkedList<Integer>();
		
		while (hasNext() && !isLineVenue() ){
			readLine();
		}	
		
		// read new venue and identify it with number
		if (hasNext()){
			
			venue = extractVenue(newLine);		
		}
		
		while (hasNext() && !isLineIndex()){
			readLine(); 		
		}				
		if (hasNext()){
			nodePartition.add(Integer.valueOf(newLine.substring(6))+1); // start indexing from 1
			readLine(); 
		}	
		
		if (venue.isEmpty()){
			venue = nodePartition.get(0).toString();
		}
		if (partitions.get(venue) == null){
			partitions.put(venue, partitionsNumber);
			partitionsNumber++;
		}	
		nodePartition.add(partitions.get(venue));
		
		while (hasNext() && !isLineVenue()){
			readLine(); 		
		}
		
		return nodePartition;
	}
}
